package interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * 交替打印A B
 * 使用 ReentrantLock+Condition
 */
public class AlternatePrint {

    public static ReentrantLock lock = new ReentrantLock();
    public static Condition printA = lock.newCondition();
    public static Condition printB = lock.newCondition();


    public static void printA(){
        lock.lock();
        try {
                System.out.println("thread-name:" + Thread.currentThread().getName()+"==output:A");
                printB.signal();
                printA.await();//一定要使用await() 切磨使用wait 采坑采坑
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void printB(){
        lock.lock();
        try {
                System.out.println("thread-name:" + Thread.currentThread().getName()+"==output:B");
                printA.signal();
                printB.await();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    //线程A
    static class PrintAThread extends Thread {

        @Override
        public void run() {
            while (true){
                printA();
            }
        }
    }

    //线程B
    static class PrintBThread extends Thread {

        @Override
        public void run() {
            while (true){
                printB();
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new PrintAThread();
        Thread t2 = new PrintBThread();
        t1.start();
        Thread.sleep(1000L);//想让A线程执行，所以休眠1秒钟
        t2.start();
    }
}
